package logic

import (
	"context"
	"errors"
	"fmt"
	"zg2_zy/zy11_cart/cartRpc/cache"
	"zg2_zy/zy11_cart/cartRpc/cart"
	"zg2_zy/zy11_cart/cartRpc/internal/svc"
	"zg2_zy/zy11_cart/cartRpc/models"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCartLogic {
	return &AddCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddCartLogic) AddCart(in *cart.AddCartRequest) (*cart.AddCartResponse, error) {
	// todo: add your logic here and delete this line

	var err error
	var g models.Goods

	g.ID = uint(in.GoodsId)
	if err = g.GetGoodsById(); err != nil {
		logx.Error("获取商品信息失败：", err)
		return nil, err
	}

	if cache.GetStockLen(int(in.GoodsId)) < in.Num {
		logx.Error("获取商品库存不足")
		return nil, errors.New("获取商品库存不足")
	}

	if in.Num > 200 {
		logx.Error("超出最大购物车数量：", errors.New("超出最大购物车数量"))
		return nil, errors.New("超出最大购物车数量")
	}

	if cache.IsExistCart(int(in.Userid), int(in.GoodsId)) {
		logx.Error("<购物车存在该商品>")
		fmt.Println("购物车存在该商品")

		cache.UpdateNum(int(in.Userid), int(in.GoodsId), in.Num)
	} else {
		fmt.Println("购物车不存在该商品")
		goodsMap := map[string]interface{}{
			"user_id":     int(in.Userid),
			"goods_id":    int(in.GoodsId),
			"goods_num":   int(in.Num),
			"goods_price": g.GoodsPrice,
			"goods_name":  g.GoodsName,
		}
		if err = cache.AddCart(int(in.Userid), int(in.GoodsId), goodsMap); err != nil {
			logx.Error("<添加入购物车失败>", err)
			return nil, errors.New("添加入购物车失败")
			return nil, err
		}
	}
	return &cart.AddCartResponse{}, nil
}
